import dingAuth from './dingAuth.js';

// 页面初始化
async function initPage() {
    try {
        // 获取当前登录用户信息
        const userInfo = await dingAuth.getCurrentUser();
        
        // 保存用户信息
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        
        // 更新用户显示信息
        updateUserDisplay(userInfo);
        
        // 根据权限更新界面
        updateUIByPermissions(userInfo.permissions);
        
        // 初始化图表
        initCharts();
    } catch (error) {
        console.error('页面初始化失败:', error);
        // 跳转到错误页面
        window.location.href = '/error.html';
    }
}

// 根据权限更新界面
function updateUIByPermissions(permissions) {
    const menuItems = document.querySelectorAll('.nav-item');
    menuItems.forEach(item => {
        const requiredPermission = item.dataset.permission;
        if (requiredPermission && !permissions.includes(requiredPermission)) {
            item.style.display = 'none';
        }
    });
}

// 更新用户显示信息
function updateUserDisplay(userInfo) {
    const userNameElement = document.querySelector('.user-info .name');
    const departmentElement = document.querySelector('.user-info .department');
    
    if (userNameElement) {
        userNameElement.textContent = userInfo.name;
    }
    if (departmentElement) {
        departmentElement.textContent = userInfo.departmentInfo[0]?.name || '';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initPage);

// 初始化所有图表
function initCharts() {
    initDepartmentChart();
    initMaintenanceChart();
    initFaultAnalysisChart();
    initDevelopmentChart();
    initTechnicalAnalysisChart();
}

// 科室故障率柱状图
function initDepartmentChart() {
    const departmentChart = echarts.init(document.getElementById('departmentChart'));
    departmentChart.setOption({
        xAxis: {
            type: 'category',
            data: ['功能科', '超声科', '检验影像科', '采血科', '临一科', '临二科', '总检诊断科']
        },
        yAxis: {
            type: 'value',
            name: '故障率(%)'
        },
        series: [{
            data: [15, 12, 20, 8, 16, 14, 18],
            type: 'bar',
            barWidth: '40%',
            itemStyle: {
                color: '#409EFF'
            }
        }],
        tooltip: {
            trigger: 'axis',
            formatter: '{b}: {c}%'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        }
    });
}

// 运维类型散点图
function initMaintenanceChart() {
    const maintenanceChart = echarts.init(document.getElementById('maintenanceChart'));
    maintenanceChart.setOption({
        xAxis: {
            type: 'category',
            data: ['设备运维', '网络运维', '系统运维']
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            type: 'scatter',
            data: [45, 280, 320]
        }]
    });
}

// 故障分析饼图
function initFaultAnalysisChart() {
    const faultAnalysisChart = echarts.init(document.getElementById('faultAnalysisChart'));
    faultAnalysisChart.setOption({
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
        },
        series: [{
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '14',
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: [
                {value: 25, name: '功能科'},
                {value: 18, name: '超声科'},
                {value: 22, name: '检验影像科'},
                {value: 12, name: '采血科'},
                {value: 15, name: '临一科'},
                {value: 14, name: '临二科'},
                {value: 20, name: '总检诊断科'}
            ]
        }]
    });
}

// 高质量发展条形图
function initDevelopmentChart() {
    const developmentChart = echarts.init(document.getElementById('developmentChart'));
    developmentChart.setOption({
        xAxis: {type: 'value'},
        yAxis: {
            type: 'category',
            data: ['互联互通', '电子病历', '智慧服务', '等级保护']
        },
        series: [{
            type: 'bar',
            data: [5, 4, 3, 3]
        }]
    });
}

// 专业技术分析雷达图
function initTechnicalAnalysisChart() {
    const technicalAnalysisChart = echarts.init(document.getElementById('technicalAnalysisChart'));
    technicalAnalysisChart.setOption({
        radar: {
            indicator: [
                {name: '医院管理系统', max: 5},
                {name: '系统及硬件', max: 5},
                {name: '前端开发', max: 5},
                {name: '数据库技术', max: 5},
                {name: '网络技术', max: 5},
                {name: '教师库技术', max: 5}
            ]
        },
        series: [{
            type: 'radar',
            data: [{
                value: [4.5, 4.2, 4.0, 4.3, 4.5, 4.1]
            }]
        }]
    });
}

// 监听窗口大小变化，调整图表大小
window.addEventListener('resize', function() {
    const charts = document.querySelectorAll('[id$="Chart"]');
    charts.forEach(chart => {
        echarts.getInstanceByDom(chart)?.resize();
    });
});

// 处理菜单点击事件
function handleMenuItemClick(pageId) {
    // 获取页面内容
    const pageContent = pageContents[pageId];
    if (!pageContent) return;

    // 更新内容区域
    const contentContainer = document.getElementById('content-container');
    const dashboardContent = document.getElementById('dashboard');
    
    // 隐藏仪表板
    if (dashboardContent) {
        dashboardContent.style.display = 'none';
    }
    
    // 显示新内容
    contentContainer.innerHTML = pageContent.content;

    // 更新标题
    document.title = `${pageContent.title} - 信息科管理系统`;
}

// 修改菜单事件监听
document.addEventListener('DOMContentLoaded', function() {
    const navItems = document.querySelectorAll('.nav-item');
    
    navItems.forEach(item => {
        const subMenu = item.querySelector('.sub-menu');
        if (subMenu) {
            item.addEventListener('click', function(e) {
                // 防止子菜单点击事件冒泡
                if (e.target.classList.contains('sub-menu-item')) {
                    return;
                }
                
                // 关闭其他打开的菜单
                navItems.forEach(otherItem => {
                    if (otherItem !== item) {
                        otherItem.classList.remove('open');
                        const otherSubMenu = otherItem.querySelector('.sub-menu');
                        if (otherSubMenu) {
                            otherSubMenu.classList.remove('open');
                            otherSubMenu.style.height = '0px';
                        }
                    }
                });

                // 切换当前菜单
                item.classList.toggle('open');
                if (item.classList.contains('open')) {
                    subMenu.classList.add('open');
                    subMenu.style.height = subMenu.scrollHeight + 'px';
                } else {
                    subMenu.classList.remove('open');
                    subMenu.style.height = '0px';
                }
            });
        }
    });

    // 处理子菜单项点击
    const subMenuItems = document.querySelectorAll('.sub-menu-item');
    subMenuItems.forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            // 移除其他活动项的激活状态
            subMenuItems.forEach(otherItem => {
                otherItem.classList.remove('active');
            });
            
            // 激活当前项
            item.classList.add('active');
            
            // 处理页面切换
            const pageId = item.dataset.page;
            if (pageId) {
                handleMenuItemClick(pageId);
            }
        });
    });
});

// 处理菜单项点击后的内容切换（示例）
function handleMenuItemClick(menuText) {
    console.log('切换到菜单:', menuText);
    // 这里可以根据菜单文本来加载对应的内容
    // 例如：通过 AJAX 请求加载内容或切换路由等
} 